package com.base.commonlib.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.StrictMode;
import android.support.multidex.MultiDex;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import com.base.commonlib.bean.DaoMaster;
import com.base.commonlib.bean.DaoSession;
import com.base.commonlib.bean.HistoryText;
import com.base.commonlib.bean.HistoryTextDao;
import com.base.commonlib.bean.Partner;
import com.base.commonlib.bean.PartnerDao;
import com.base.commonlib.bean.RoadEntity;
import com.base.commonlib.bean.RoadEntityDao;
import com.base.commonlib.bean.User;
import com.base.commonlib.bean.UserDao;
import com.base.commonlib.bean.UserRoad;
import com.base.commonlib.bean.UserRoadDao;
import com.base.commonlib.config.MvpConstants;
import com.base.commonlib.event.RoadEvent;
import com.base.commonlib.http.utils.ErrorLogUtil;
import com.base.commonlib.utils.MineOpenHelper;
import com.base.commonlib.utils.MineRoadUtil;
import com.base.commonlib.utils.RxBus2;
import com.base.commonlib.utils.ToastUtil;
import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsListener;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import retrofit2.http.PUT;

/**
 * Date：2019/4/9 下午3:05
 * Creator：arvin
 * Des：
 */

public class BaseApp extends Application implements Thread.UncaughtExceptionHandler{

    protected static LinkedList<Activity> sActivities = new LinkedList<>();
    public static Context sAppContext;
    private static DaoSession mDaoSession;
    public static int SCREEN_WIDTH = -1;
    public static int SCREEN_HEIGHT = -1;
    public static float DIMEN_RATE = -1.0F;
    public static int DIMEN_DPI = -1;


    /**
     * 屏幕宽度
     */
    public static int screenWidth;
    /**
     * 屏幕高度
     */
    public static int screenHeight;
    /**
     * 屏幕密度
     */
    public static float screenDensity;

    @Override
    public void onCreate() {
        super.onCreate();

        sAppContext = getApplicationContext();
        initScreenSize();
        //非wifi情况下，主动下载x5内核
        QbSdk.setDownloadWithoutWifi(true);
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("tag", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
                Log.d("tag", " onCoreInitFinished");
            }
        };


        //x5内核初始化接口

        QbSdk.setTbsListener(new TbsListener() {
            @Override
            public void onDownloadFinish(int i) {
                Log.e("xxxx","onDownloadFinish  "+i);
            }

            @Override
            public void onInstallFinish(int i) {
                Log.e("xxxx","onInstallFinish  "+i);
            }

            @Override
            public void onDownloadProgress(int i) {
                Log.e("xxxx","onDownloadProgress  "+i);
            }
        });
        QbSdk.initX5Environment(sAppContext, cb);

        //7.0文件路径权限适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
        //
        initGreenDao();
        Thread.setDefaultUncaughtExceptionHandler(this);
        ToastUtil.getInstance(this);
        //初始化屏幕宽高
        getScreenSize();

        UMConfigure.init(this, "5e53256305738a6aa305c4d3"
                , "umeng",UMConfigure.DEVICE_TYPE_PHONE,"");
        PlatformConfig.setWeixin("wx8469668f067ceae1", "be8a474d2b7c48f615d5770825cda007");
        //豆瓣RENREN平台目前只能在服务器端配置
        PlatformConfig.setSinaWeibo("1634659907", "f4bcda93e80547be532557a1ea0f550b", "http://sns.whalecloud.com");
        PlatformConfig.setQQZone("1110195363", "Jie7CmuWQ00UR0Cr");
        PlatformConfig.setAlipay("2015111700822536");
        PlatformConfig.setDing("dingoalmlnohc0wggfedpk");
    }
    /**
     * 初始化当前设备屏幕宽高
     */
    private void initScreenSize() {
        DisplayMetrics curMetrics = getApplicationContext().getResources().getDisplayMetrics();
        screenWidth = curMetrics.widthPixels;
        screenHeight = curMetrics.heightPixels;
        screenDensity = curMetrics.density;
    }

    public static void addActivity(Activity activity) {
        if (!sActivities.contains(activity)) {
            sActivities.add(activity);
        }
    }

    public static void removeActivity(Activity activity) {
        if (sActivities.contains(activity)) {
            sActivities.remove(activity);
        }
    }

    public static void clearActivity() {
        for (Activity activity : sActivities) {
            activity.finish();
        }
        sActivities.clear();
    }
    public static int getActivitySize()
    {
        return sActivities.size();
    }

    public static void exit() {
        clearActivity();
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        clearActivity();
        try {
            ErrorLogUtil.saveError(getApplicationContext(), e);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private void initGreenDao() {
        MineOpenHelper sip_complex = new MineOpenHelper(this, MvpConstants.DB_NAME);
        SQLiteDatabase db = sip_complex.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        mDaoSession = daoMaster.newSession();

    }
    public static DaoSession getDaoSession() {
        mDaoSession.clear();
        return mDaoSession;
    }
    public static Context getApp()
    {
        return sAppContext;
    }





    public static void saveUser(User user){
        DaoSession daoSession = BaseApp.getDaoSession();
        UserDao userDao = daoSession.getUserDao();
        userDao.deleteAll();
        userDao.insert(user);
    }
    public static User getUser(){
        try {
            DaoSession daoSession = BaseApp.getDaoSession();
            UserDao userDao = daoSession.getUserDao();
            List<User> users = userDao.loadAll();
            return users.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void setPatter(Partner partner,User mUser){
            try {
                PartnerDao partnerDao = BaseApp.getDaoSession().getPartnerDao();
                QueryBuilder<Partner> partnerQueryBuilder = partnerDao.queryBuilder();
                List<Partner> list = partnerQueryBuilder.where(PartnerDao.Properties.ParentId.eq(mUser.getUserId())).list();
                if(list!=null)
                {
                    partnerDao.deleteInTx(list);
                }
                partner.setParentId(mUser.getUserId());
                partnerDao.insert(partner);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    public void getScreenSize(){
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        Display display = windowManager.getDefaultDisplay();
        display.getMetrics(dm);
        DIMEN_RATE = dm.density / 1.0F;
        DIMEN_DPI = dm.densityDpi;
        SCREEN_WIDTH = dm.widthPixels;
        SCREEN_HEIGHT = dm.heightPixels;
        if(SCREEN_WIDTH > SCREEN_HEIGHT) {
            int t = SCREEN_HEIGHT;
            SCREEN_HEIGHT = SCREEN_WIDTH;
            SCREEN_WIDTH = t;
        }

    }

    public static List<RoadEntity> getMineRoad(String userId){
        RoadEntityDao roadEntityDao = BaseApp.getDaoSession().getRoadEntityDao();
        List<RoadEntity> roadEntities = roadEntityDao.loadAll();
        return MineRoadUtil.getMineRoads(userId);
    }
    public static List<RoadEntity> getMineRoadEntities(){
        RoadEntityDao roadEntityDao = BaseApp.getDaoSession().getRoadEntityDao();
        List<RoadEntity> roadEntities = roadEntityDao.loadAll();
        return roadEntities;
    }
    public static void insertRoad(List<RoadEntity> roads){
        RoadEntityDao roadEntityDao = BaseApp.getDaoSession().getRoadEntityDao();
        roadEntityDao.deleteAll();
        roadEntityDao.insertInTx(roads);
    }
    public static void setUserRoad(String userId,List<RoadEntity> mMineRoads){
        DaoSession daoSession = BaseApp.getDaoSession();
        UserRoadDao userRoadDao = daoSession.getUserRoadDao();
        QueryBuilder<UserRoad> userRoadQueryBuilder = userRoadDao.queryBuilder();
        List<UserRoad> list_userroads = userRoadQueryBuilder.where(UserRoadDao.Properties.UserId.eq(userId)).list();
        userRoadDao.deleteInTx(list_userroads);
        ArrayList<UserRoad> userRoads = new ArrayList<>();
        for (RoadEntity item : mMineRoads) {
            UserRoad userRoad = new UserRoad();
            userRoad.setUserId(userId);
            userRoad.setRoadNo(item.getRoadNo());
            userRoads.add(userRoad);
        }
        userRoadDao.insertInTx(userRoads);
        RxBus2.getInstance().post(new RoadEvent());
    }

    public static void updataRoad(List<RoadEntity> roads)
    {
        RoadEntityDao roadEntityDao = BaseApp.getDaoSession().getRoadEntityDao();
        roadEntityDao.deleteAll();
        roadEntityDao.insertInTx(roads);
    }
    public static void setPatters(List<Partner> partner,User mUser){
        try {
            PartnerDao partnerDao = BaseApp.getDaoSession().getPartnerDao();
            QueryBuilder<Partner> partnerQueryBuilder = partnerDao.queryBuilder();
            List<Partner> list = partnerQueryBuilder.where(PartnerDao.Properties.ParentId.eq(mUser.getUserId())).list();
            if(list!=null)
            {
                partnerDao.deleteInTx(list);
            }
            for (Partner mPartner : partner){
                mPartner.setParentId(mUser.getUserId());
                partnerDao.insert(mPartner);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Partner getPartner(){
        DaoSession daoSession = BaseApp.getDaoSession();
        UserDao userDao = daoSession.getUserDao();
        List<User> users = userDao.loadAll();
        User user = users.get(0);
        QueryBuilder<Partner> partnerQueryBuilder = daoSession.getPartnerDao().queryBuilder();
        return partnerQueryBuilder.where(PartnerDao.Properties.ParentId.eq(user.getUserId())).unique();
    }
    public static List<Partner> getPartners(){

        try {
            DaoSession daoSession = BaseApp.getDaoSession();
            UserDao userDao = daoSession.getUserDao();
            List<User> users = userDao.loadAll();
            User user = users.get(0);
            QueryBuilder<Partner> partnerQueryBuilder = daoSession.getPartnerDao().queryBuilder();
            return partnerQueryBuilder.where(PartnerDao.Properties.ParentId.eq(user.getUserId())).list();
        }catch (Exception e){
            e.printStackTrace();
            List<Partner> list = new ArrayList<>();
            return list;
        }

    }
    public static void setHistoryText(String userId,String text){
        DaoSession daoSession = BaseApp.getDaoSession();
        HistoryTextDao dao = BaseApp.getDaoSession().getHistoryTextDao();
        QueryBuilder<HistoryText> partnerQueryBuilder = daoSession.getHistoryTextDao().queryBuilder();
        List<HistoryText> list = partnerQueryBuilder.where(HistoryTextDao.Properties.UserId.eq(userId)).list();
        for (HistoryText text1 : list){
            if (text1.getText().equals(text)){
                dao.delete(text1);
            }
        }
        if (list.size()>50){
            for (int i=50;i<list.size();i++){
                dao.delete(list.get(i));
            }
        }
        HistoryText historyText = new HistoryText();
        historyText.setData(System.currentTimeMillis()+"");
        historyText.setTextId(UUID.randomUUID()+"");
        historyText.setUserId(userId);
        historyText.setText(text);
        dao.insert(historyText);
    }
    public static List<HistoryText> gethistoryText(String userId,int size){
        DaoSession daoSession = BaseApp.getDaoSession();
        QueryBuilder<HistoryText> partnerQueryBuilder = daoSession.getHistoryTextDao().queryBuilder();
        return partnerQueryBuilder.where(HistoryTextDao.Properties.UserId.eq(userId)).distinct().limit(size).list();
    }
}

